package com.ksyun.ks3.services;

import com.ksyun.ks3.services.handler.AsyncHttpResponseHandler;
import com.ksyun.ks3.services.handler.ProgressResponseBody;
import com.ksyun.ks3.services.request.ProgressRequestBody;

import java.io.IOException;
import java.io.InputStream;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;

public class NetworkProgressHelper {
    /**
     * add response progress
     * @param client
     * @param handler
     * @return
     */
    public static OkHttpClient addProgressResponseListener (OkHttpClient client, final AsyncHttpResponseHandler handler) {
        OkHttpClient build = client.newBuilder().addNetworkInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new ProgressResponseBody(originalResponse.body(), handler))
                        .build();
            }
        }).build();
        return build;
    }

    /**
     * add request progress
     * @param input
     * @param contentLength
     * @param contentType
     * @param handler
     * @return
     */
    public static ProgressRequestBody addProgressRequestBody (InputStream input,
                                                              long contentLength,
                                                              String contentType,
                                                              AsyncHttpResponseHandler handler) {
        return new ProgressRequestBody(input, contentLength, contentType, handler);
    }
}
